package cn.ddiancan.xddcloud.ddccore.validator;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Objects;

import cn.ddiancan.xddcloud.ddccore.validator.annotation.DateNotBefore;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
public class DateNotBeforeValidator implements ConstraintValidator<DateNotBefore, Object> {

    private String targetDate;

    private String sourceDate;

    private String message;

    @Override
    public void initialize(DateNotBefore constraintAnnotation) {
        targetDate = constraintAnnotation.targetDate();
        sourceDate = constraintAnnotation.sourceDate();
        message = constraintAnnotation.message();
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        Date source;
        Date target;
        try {
            if (!StringUtils.hasText(targetDate) && !StringUtils.hasText(sourceDate)) {
                return true;
            }
            if (!StringUtils.hasText(targetDate)) {
                Field sourceField = value.getClass().getDeclaredField(sourceDate);
                sourceField.setAccessible(true);
                source = (Date) sourceField.get(value);
                target = new Date();
            } else if (!StringUtils.hasText(sourceDate)) {
                source = new Date();
                Field targetField = value.getClass().getDeclaredField(targetDate);
                targetField.setAccessible(true);
                target = (Date) targetField.get(value);
            } else {
                Field sourceField = value.getClass().getDeclaredField(sourceDate);
                Field targetField = value.getClass().getDeclaredField(targetDate);
                sourceField.setAccessible(true);
                targetField.setAccessible(true);
                source = (Date) sourceField.get(value);
                target = (Date) targetField.get(value);
            }
            if (Objects.nonNull(source) && Objects.nonNull(target)) {
                return source.before(target);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("日期校验失败:{}", e.getMessage());
        } catch (IllegalArgumentException e) {
            log.error("非法参数: {}", e.getMessage(), e);
        } catch (SecurityException e) {
            log.error("安全异常: {}", e.getMessage(), e);
        }
        return true;
    }
}
